/*
 * Filename:    RandomCodeUtil.java
 * Copyright:   2014 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2014-12-29
 */
package com.paic.mhis.hcpms.audit.biz.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.paic.mhis.common.cache.biz.service.BigShareCache;
import com.paic.mhis.hcpms.audit.biz.service.RandomCodeService;
import com.paic.mhis.hcpms.audit.dao.EventCodeDao;
import com.paic.mhis.hcpms.audit.dto.EventCodeDTO;
import com.paic.mhis.hcpms.audit.util.RandomCodeUtil;

/**
 * @author EX-PANAN001
 * 
 */
@Service("randomCodeService")
public class RandomCodeServiceImpl implements RandomCodeService {
	private Log log = LogFactory.getLog(this.getClass());

	@Resource
	private BigShareCache redisShareCache;

	@Autowired
	private EventCodeDao eventCodeDao;

	/**
	 * 获取生成的问题编号
	 * 
	 * @param str
	 * @param industry_type
	 * @return
	 */
	@Override
	public String getCode(String str, String industry_type) {
		String initCode = initCode(str, industry_type);
		return initCode;
	}

	private boolean addCodeInCache(String code, String industry_type) {
		boolean indb = true;
		boolean addedToCache = false;
		List<String> list = null;
		list = eventCodeDao.getQuestionCode("queryEventCode", industry_type);
		indb = list.contains(code);
		if (!indb) {
			final String cacheKey = "hcpms.Casecode";
			addedToCache = redisShareCache.sadd(cacheKey, 0, code);
		}
		return addedToCache;
	}

	/**
	 * 根据业务类型查询所有已生成生成的编号，确定此编号可用
	 * 
	 * @param str
	 * @return
	 */
	public synchronized String initCode(String str, String industry_type) {
		// 获取随机编号
		String randomCode = null;
		// 获取所有已经存在的编号,判断新生成的编号是否可用
		randomCode = RandomCodeUtil.getRandomCode(str);

		int limit = 100;
		int index = 0;
		while (!addCodeInCache(randomCode, industry_type) && index < limit) {
			randomCode = RandomCodeUtil.getRandomCode(str);
			index++;
		}
		if (index >= 100) {
			randomCode = null;
		}

		EventCodeDTO eventCode = new EventCodeDTO();
		if (null != randomCode) {
			eventCode.setQuestionCode(randomCode);
			eventCode.setIndustryType(industry_type);
			eventCode.setIndustryDate(new SimpleDateFormat(
					"yyyy-MM-dd hh:mm:ss").format(new Date()));
			eventCodeDao.insertQuestionCode(eventCode);
		}
		return eventCode.getQuestionCode();
	}
}
